package com.xuan.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.xuan.constants.CommonConstants.USER_TOKEN_PREFIX;
import static com.xuan.constants.CommonConstants.USER_TOKEN_TTL;

@Slf4j(topic = "RefreshTokenHandler")
public class RefreshTokenHandler implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenHandler(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization"); // 获取请求头中的token
        log.info("获取请求中的token: {}", token);
        String tokenKey = USER_TOKEN_PREFIX + token;
        String email = stringRedisTemplate.opsForValue().get(tokenKey);
        // 刷新过期时间
        stringRedisTemplate.expire(tokenKey, USER_TOKEN_TTL, TimeUnit.SECONDS);
        // 放行
        return true;
    }
}
